import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Params, Router} from '@angular/router';
import {SearchResultService} from './search-result.service';
import {SearchResult} from '../content/model/search-result';
import _ from 'lodash';
import {timer} from 'rxjs';
import {NzTreeComponent, NzTreeNode, NzTreeNodeOptions} from 'ng-zorro-antd/tree';

@Component({
  selector: 'app-search-result',
  templateUrl: './search-result.component.html',
  styleUrls: ['./search-result.component.less']
})
export class SearchResultComponent implements OnInit, AfterViewInit {
  searchCondition = new SearchResult();
  wordFreamFourId = [];
  wordFreamList = [];
  wordFreamCounts = [];
  regions = [];
  years = [];
  key = [];
  tags = [];
  articleData = '';
  articleTotal = 0;
  treeNodes: NzTreeNodeOptions[] = [];
  isSpinning;
  // 从首页传来的原始搜索key
  originalKey;
  countWithYear;
  countWithRegion;
  countWithPublishOrgan;
  spreadResponse;
  policyKetwordYuntu;
  publishOrganSpreadResponse;
  chartIsShow = false;
  @ViewChild('wordFrameTree') wordFrameTree!: NzTreeComponent;

  constructor(private route: ActivatedRoute,
              private searchService: SearchResultService,
              private router: Router) {
  }

  ngOnInit(): void {
    this.route.queryParams.pipe().subscribe((params: Params) => {
      this.isSpinning = true;
      if (params) {
        this.searchCondition.key = [];
        this.searchCondition.key.push(params.key);
        this.originalKey = params.key;
        this.searchService.searchArticle(this.searchCondition).subscribe(res => {
          if (res.result) {
            this.chartIsShow = true;
            // 将找到的关键词替换为高亮的富文本样式显示出来
            const re = new RegExp('' + params.key, 'gi');
            const replaceString = '<span class="heightLight">' + params.key + '</span>';
            for (let i = 0; i < res.result.policys.list.length; i++) {
              res.result.policys.list[i].searchContent = _.replace(res.result.policys.list[i].searchContent, re, replaceString);
            }
            // 要传递到矩阵页面的tab信息（四级词表）
            this.wordFreamFourId = [];
            for (const word of res.result.wordFream4List) {
              this.wordFreamFourId.push(JSON.stringify({id: word.id, label: word.label}));
            }
            this.wordFreamCounts = res.result.wordFreamCounts;
            this.articleData = res.result.policys.list;
            this.articleTotal = res.result.policys.total;
            this.countWithYear = res.result.countWithYear;
            this.countWithRegion = res.result.countWithRegion;
            this.countWithPublishOrgan = res.result.countwithPublishOrgan;
            this.spreadResponse = res.result.spreadResponse;
            this.policyKetwordYuntu = res.result.policyKetwordYuntu;
            this.publishOrganSpreadResponse = res.result.publishOrganSpreadResponse;
          }
          this.getTreeData();
        });
        this.updateChecks(params.key);
      }
    });
  }

  // 更新复选框区域内容
  updateChecks(key: string = null, id: string = null) {
    this.searchService.searchChecks(key, id).subscribe(res => {
      if (res.result) {
        this.regions = [];
        this.years = [];
        this.key = [];
        for (const region of res.result.regions) {
          this.regions.push({label: region, value: region});
        }
        for (const year of res.result.years) {
          this.years.push({label: year, value: year});
        }
        for (const item of res.result.key) {
          if (this.originalKey != null && this.originalKey === item) {
            this.key.push({label: item, value: item, checked: true});
          } else {
            this.key.push({label: item, value: item});
          }
        }
      }
    });
  }

  // 展开父节点，因为树组件要想把子节点展开并暴露出来，必须让其上的所有父节点都展开
  expandNode(node: NzTreeNode) {
    // 只展开到三级节点，叶子节点这一级不展开
    if (!node.isLeaf) {
      const pNode = node.getParentNode();
      if (pNode) {
        pNode.isExpanded = true;
        this.expandNode(pNode);
      } else {
        return;
      }
    }
  }

  clickBoxRegions(event: any) {
    this.searchCondition.regions = [];
    for (const item of event) {
      if (item.checked) {
        this.searchCondition.regions.push(item.value);
        this.tags.push({label: item.label, value: item.value, prefix: '地域：'});
        this.tags = _.uniqBy(this.tags, 'value');

      } else {
        _.remove(this.tags, {value: item.value});
      }
    }
    this.clickSearch();
  }

  clickBoxYears(event: any) {
    this.searchCondition.years = [];
    for (const item of event) {
      if (item.checked) {
        this.searchCondition.years.push(item.value);
        this.tags.push({label: item.label, value: item.value, prefix: '年份：'});
        this.tags = _.uniqBy(this.tags, 'value');

      } else {
        _.remove(this.tags, {value: item.value});
      }
    }
    this.clickSearch();
  }

  clickBoxKey(event: any) {
    this.searchCondition.key = [];
    for (const item of event) {
      if (item.checked) {
        this.searchCondition.key.push(item.value);
        this.tags.push({label: item.label, value: item.value, prefix: null});
        this.tags = _.uniqBy(this.tags, 'value');

      } else {
        _.remove(this.tags, {value: item.value});
      }
    }
    this.clickSearch();
  }

  clickSearch() {
    this.chartIsShow = false;
    this.isSpinning = true;
    this.searchService.searchArticle(this.searchCondition).subscribe(res => {
      if (res.result) {
        this.chartIsShow = true;
        this.articleData = res.result.policys.list;
        this.articleTotal = res.result.policys.total;
        this.countWithYear = res.result.countWithYear;
        this.countWithRegion = res.result.countWithRegion;
        this.countWithPublishOrgan = res.result.countwithPublishOrgan;
        this.spreadResponse = res.result.spreadResponse;
        this.policyKetwordYuntu = res.result.policyKetwordYuntu;
        this.publishOrganSpreadResponse = res.result.publishOrganSpreadResponse;
        // 要传递到矩阵页面的tab信息（四级词表）
        this.wordFreamFourId = [];
        for (const word of res.result.wordFream4List) {
          this.wordFreamFourId.push(JSON.stringify({id: word.id, label: word.label}));
        }
      }
      this.isSpinning = false;
    });
  }

  // // 删除标签
  // onClose(tag: any) {
  //
  // }

  toMatrix() {
    this.router.navigate(['/policy-analysis-matrix'], {
      queryParams: {
        // policy: this.paramWord,
        // region: this.searchCondition.regions,
        // key: this.searchCondition.key,
        wordFrameFourId: this.wordFreamFourId,
        condition: JSON.stringify(this.searchCondition)
      }
    });
  }

  // 树
  getTreeData() {
    this.searchService.getTreeData().subscribe(res => {
      this.treeNodes = res.result;
      timer(500).subscribe(() => {
        this.updateOnTreeNum();
      });
    });
  }

  // 更新树节点上的数字
  updateOnTreeNum() {
    // 根据后台返回的节点key和count，找到相应节点，改变它的显示title并加富文本数字后缀、展开它
    for (const wordFreamCount of this.wordFreamCounts) {
      if (wordFreamCount.key !== null) {
        const treeNode = this.wordFrameTree.getTreeNodeByKey(wordFreamCount.key);
        treeNode.title += `<font class="markNumber">(${wordFreamCount.count})</font>`;
        this.expandNode(treeNode);
      }
    }
    this.isSpinning = false;

  }

  // 使顶级框架词样式突显
  topWordBold(node: NzTreeNode) {
    return node.getParentNode() instanceof NzTreeNode;
  }

  treeClick(event: any) {
    this.chartIsShow = false;
    this.isSpinning = true;
    this.searchCondition.key = [];
    this.searchCondition.key.push(this.originalKey);
    this.searchCondition.wordFreamId = [];
    this.searchCondition.wordFreamId.push(event.node.origin.id);
    this.searchService.searchArticle(this.searchCondition).subscribe(res => {
      if (res.result) {
        this.chartIsShow = true;
        this.articleData = res.result.policys.list;
        this.wordFreamCounts = res.result.wordFreamCounts;
        this.articleTotal = res.result.policys.total;
        this.countWithYear = res.result.countWithYear;
        this.countWithRegion = res.result.countWithRegion;
        this.countWithPublishOrgan = res.result.countwithPublishOrgan;
        this.spreadResponse = res.result.spreadResponse;
        this.policyKetwordYuntu = res.result.policyKetwordYuntu;
        this.publishOrganSpreadResponse = res.result.publishOrganSpreadResponse;
        // 要传递到矩阵页面的tab信息（四级词表）
        this.wordFreamFourId = [];
        for (const word of res.result.wordFream4List) {
          this.wordFreamFourId.push(JSON.stringify({id: word.id, label: word.label}));
        }
      }
      this.getTreeData();
    });
    this.updateChecks(this.originalKey, this.searchCondition.wordFreamId.toString());

  }

  // 阻止a链接的冒泡行为
  stopBubbling(event: any) {
    event.stopPropagation();
  }

  ngAfterViewInit() {
  }
}
